package response

import (
	"gdshop-font-api-go/library/tools/version"
	"github.com/gogf/gf/container/gmap"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
)

// 数据返回通用JSON数据结构
type JsonResponse struct {
	Code    int         `json:"code"`    // 错误码((0:成功, 1:失败, >1:错误码))
	Message string      `json:"message"` // 提示信息
	Version string      `json:"version"` // 当前版本
	Data    interface{} `json:"data"`    // 返回数据(业务接口定义具体数据结构)
}

// 标准返回结果数据结构封装。
func Json(r *ghttp.Request, code int, message string, data ...interface{}) {
	responseData := interface{}(nil)
	if len(data) > 0 {
		responseData = data[0]
	}
	r.Response.WriteJson(JsonResponse{
		Code:    code,
		Message: message,
		Version: version.GetVersion(r, g.Cfg().GetString("site.ApiVersionName")),
		Data:    responseData,
	})
}

// 返回JSON数据并退出当前HTTP执行函数。
func JsonExit(r *ghttp.Request, code int, msg string, data ...interface{}) {
	Json(r, code, msg, data...)
	r.Exit()
}

func SuccessByRequest(r *ghttp.Request) *JsonResponse {
	return JsonByAll(r, 0, "Success")
}

func SuccessByRequestMessage(r *ghttp.Request, message string) *JsonResponse {
	return JsonByAll(r, 0, message)
}
func SuccessByRequestMessageData(r *ghttp.Request, message string, data interface{}) *JsonResponse {
	return JsonByAll(r, 0, message, data)
}

func JsonByAll(r *ghttp.Request, code int, message string, data ...interface{}) *JsonResponse {
	responseData := interface{}(nil)
	if len(data) > 0 {
		responseData = data[0]
	}
	versionStr := ""
	if r != nil {
		versionStr = version.GetVersion(r, g.Cfg().GetString("site.ApiVersionName"))
	}
	if responseData == nil {
		responseData = gmap.Map{}
	}
	return &JsonResponse{
		Code:    code,
		Message: message,
		Data:    responseData,
		Version: versionStr,
	}
}

func FailByRequest(r *ghttp.Request) *JsonResponse {
	return FailByRequestMessage(r, "Error")
}
func FailByRequestMessage(r *ghttp.Request, message string) *JsonResponse {
	return JsonByAll(r, 1, message)
}

func FailByRequestRateLimiter(r *ghttp.Request, messages ...string) *JsonResponse {
	msg := "请求太频繁"
	if len(messages) > 0 {
		msg = messages[0]
	}
	return JsonByAll(r, -99, msg)
}

func RpcFailByRequestMessage(r *ghttp.Request, message string) *JsonResponse {
	if message == "EOF" || message == "timeout" {
		return FailByRequestMessage(r, "RPC通讯秘钥错误")
	}
	return FailByRequestMessage(r, message)
}
